package org.zjt.demo.service.imp;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.zjt.demo.dao.TestDao;
import org.zjt.demo.model.TestPOJO;
import org.zjt.demo.service.ITestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  1、同一个类中，有A、B两个函数
 *      A调用B函数，B函数有事务的话，A函数没有事务，此时事务不起作用。
 *
 *  事务：
 *      1、Scope
 */
@Service
//@Scope("prototype")
public class TestServiceImp implements ITestService{

    @Autowired
    private TestDao testDao;



    @Override
    public List<TestPOJO> get(Long age) {


        /*List<TestPOJO> data=new ArrayList<>(2);
        TestPOJO pojo=new TestPOJO();
        pojo.setAge(11);
        pojo.setId(1L);
        pojo.setName("zhangsan");
        data.add(pojo);
        return  data;*/
        return testDao.get(age);
    }

    @Transactional
    public void updateUser(TestPOJO pojo){
        testDao.update(pojo);
       // int i = 1/0;

    }


    // TODO: 2017/5/11 select for update 必须保证方法的执行的被访问的执行的一致性。 
     AtomicInteger num = new AtomicInteger(0);


    @Transactional(isolation= Isolation.READ_UNCOMMITTED)
    public void concurrentUpdata(TestPOJO pojo)throws Exception{
        TestPOJO pojo1 = testDao.get(pojo.getId()).get(0);
        System.out.println(JSONObject.toJSONString(pojo1));
        pojo1.setAge(pojo1.getAge()+1);
        try {
            Thread.sleep(num.get()%2 == 0 ? 10000 :500);
        }catch (Exception e){
        }

        System.out.println(num.incrementAndGet());
        testDao.update(pojo1); //131

        // int i = 1/0;

    }

}
